package com.example.springaidemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.springaidemo.model.ChatMessage;
import com.example.springaidemo.model.ChatSession;
import com.example.springaidemo.service.ChatSessionService;
import java.util.List;

@Service
public class AiService {

    private final DeepSeekService deepSeekService;
    private final BailianService bailianService;
    private final ChatSessionService chatSessionService;

    @Autowired
    public AiService(DeepSeekService deepSeekService, BailianService bailianService, ChatSessionService chatSessionService) {
        this.deepSeekService = deepSeekService;
        this.bailianService = bailianService;
        this.chatSessionService = chatSessionService;
    }

    // 生成内容方法
    public String generateContentWithDeepSeek(String prompt) {
        return deepSeekService.generateContent(prompt);
    }

    public String generateContentWithBailian(String prompt) {
        return bailianService.generateContent(prompt);
    }

    // 聊天方法
    public String chatWithDeepSeek(String message) {
        return deepSeekService.chat(message);
    }

    public String chatWithBailian(String message) {
        return bailianService.chat(message);
    }

    // 默认方法，使用DeepSeek作为默认
    public String generate(String prompt) {
        return deepSeekService.generateContent(prompt);
    }

    public String chat(String message) {
        return deepSeekService.chat(message);
    }
    
    // 多轮对话相关方法
    
    // 创建新会话
    public ChatSession createNewSession() {
        return chatSessionService.createSession();
    }
    
    // 使用DeepSeek进行多轮对话
    public String chatWithDeepSeekHistory(String sessionId, String message) {
        // 获取会话历史
        List<ChatMessage> history = chatSessionService.getMessagesFromSession(sessionId);
        
        // 调用DeepSeek的多轮对话方法
        String response = deepSeekService.chatWithHistory(message, history);
        
        // 将用户消息和AI响应保存到会话历史
        chatSessionService.addMessageToSession(sessionId, "user", message);
        chatSessionService.addMessageToSession(sessionId, "assistant", response);
        
        return response;
    }
    
    // 使用百炼进行多轮对话
    public String chatWithBailianHistory(String sessionId, String message) {
        // 获取会话历史
        List<ChatMessage> history = chatSessionService.getMessagesFromSession(sessionId);
        
        // 调用百炼的多轮对话方法
        String response = bailianService.chatWithHistory(message, history);
        
        // 将用户消息和AI响应保存到会话历史
        chatSessionService.addMessageToSession(sessionId, "user", message);
        chatSessionService.addMessageToSession(sessionId, "assistant", response);
        
        return response;
    }
    
    // 默认多轮对话方法
    public String chatWithHistory(String sessionId, String message) {
        return chatWithDeepSeekHistory(sessionId, message);
    }
}